using System;
using SoftwareMonkeys.Scriptech.Diagnostics;
using SoftwareMonkeys.Scriptech.Scripts;
using System.Web;
using System.Configuration;

namespace SoftwareMonkeys.Scriptech.Web
{
	/// <summary>
	/// Description of ErrorHandler.
	/// </summary>
	public class ExceptionHandler
	{
		public ExceptionHandler()
		{
		}
		
		
		public void Handle(Exception exception)
		{	
			string newPath = String.Empty;
			
			using (LogGroup logGroup = LogGroup.StartDebug("Handling error."))
			{
				if (exception != null)
				{
					try
					{						
						if (HttpContext.Current != null && HttpContext.Current.Session != null)
							HttpContext.Current.Session["LastException_ReferringScript"] = ScriptsUtil.GetCurrentScript ();
						
						LogWriter.Error(exception);
						
						// TODO: Re-enable send mail function
					//	SendEmail(exception);
	
						string setting = ConfigurationSettings.AppSettings["EnableErrorHandling"];
						if (setting != null && setting != String.Empty && Convert.ToBoolean(setting))
						{							
							newPath = GetNewPath(exception);
							
							LogWriter.Debug("New path: " + newPath);
							
							LogWriter.Debug("Error handling is enabled. Redirecting to error page.");
							
						}
						else
						{
							LogWriter.Debug("Error handling is disabled");
							throw exception;
						}
					}
					catch (Exception ex)
					{
						using (LogGroup logGroup2 = LogGroup.StartDebug("Error handling failed. There was an error within the error handling itself."))
						{
							LogWriter.Error(ex);
						}
					}
				}
				else
					LogWriter.Debug("No exception provided. Skipping.");
			}
			
			// Send the user to the error age outside of the log group if they aren't already there
			if (HttpContext.Current.Request.Url.ToString().ToLower().IndexOf("error.aspx") == -1)
			{
				//Redirector.Go(newPath, true);
				// Use Response.Redirect because it doesn't matter if it shows the error page in the URL
				HttpContext.Current.Response.Redirect(newPath, false);
			}
		}
		
		private string GetNewPath(Exception exception)
		{
			string queryString = "";
			
			queryString = GetQueryStrings();
			
			string errorPage = "Error.aspx";
			if (exception is ScriptNotFoundException)
				errorPage = "ScriptNotFound.aspx";
			
			string newPath = HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/" + errorPage + queryString;	
			
			return newPath;
		}
		
		private string GetQueryStrings()
		{			
			string queryString = String.Empty;
			
			string referringScript = ScriptsUtil.GetCurrentScript();
			
			if (referringScript != String.Empty)
				queryString = "?ReferringScript=" + referringScript.Replace("?", "&");
			
			string originalQueryString = HttpContext.Current.Request.Url.Query;
			
			return queryString;
		}
		                               
		
		/*public void SendEmail(Exception exception)
		{
			try
			{
				if (new ModeDetector().IsRelease)
				{
					UserRole role = RetrieveStrategy.New<UserRole>(false).Retrieve<UserRole>("Name", "Administrator");
					
					ActivateStrategy.New(role, false).Activate(role, "Users");
					
					foreach (User user in role.Users)
					{
						string subject = "Exception";
						string message = "An exception occurred...\n"
							+ "URL:\n"
							+ HttpContext.Current.Request.Url.ToString() + "\n\n"
							+ "Site:\n"
							+ WebUtilities.ConvertRelativeUrlToAbsoluteUrl(HttpContext.Current.Request.ApplicationPath) + "\n\n"
							+ "Time:\n"
							+ DateTime.Now.ToLongDateString() + " - " + DateTime.Now.ToLongTimeString() + "\n\n"
							+ "Exception:\n"
							+ exception.ToString() + "\n\n"
							+ "(please do not reply to this email)\n";
						
						Emailer.New().SendEmail(user, subject, message);
					}
				}
			}
			catch(Exception ex)
			{
				//LogWriter.Error("Exception occurred when trying to send error report email.");
				
				//LogWriter.Error(ex);
			}
		}*/
	}
}

